#! -*- coding:utf-8 -*-
import os
import sys
import json
import time
import fcntl
import logging
import requests

from common.cache import redis_cache
from common.withdraw.just_withdraw import generate_sign

from django.conf import settings
from django.core.management.base import BaseCommand

_LOGGER = logging.getLogger('worker')


class Command(BaseCommand):
    def handle(self, **kwargs):
        """
        {"msg": "", "status": 0, "data": {"types_limist": {"jd": {"max": 999, "min": 1}, "qq": {"max": 3000, "min": 5},
         "unionpay": {"max": 999, "min": 1}, "alipay": {"max": 3000, "min": 10}}, "wx_quotas": [50.0, 60.0],
          "list": ["recharge_card", "jd", "unionpay", "quota_alipay", "qq", "quota_wxpay", "alipay"],
          "quotas": [1.0, 10.0, 100.0, 1000.0, 2000.0, 1000000.0, 11111111111.0, 2.0, 3.0]}}'
        :param kwargs:
        :return:
        """
        while True:
            try:
                parameter_dict = {
                    'mch_id': settings.JUSTPAY_MCH_ID,
                }
                parameter_dict['sign'] = generate_sign(parameter_dict, settings.JUSTPAY_API_KEY)
                res = requests.post(settings.QUERY_URL, data=parameter_dict, timeout=5).text
                res = json.loads(res)
                pay_list = res['data']['list']
                quotas = res['data'].get('quotas')
                wx_quotas = res['data'].get('wx_quotas')
                redis_cache.set_available_pays(*pay_list)
                if quotas:
                    redis_cache.set_alipay_quotas(*quotas)
                if wx_quotas:
                    redis_cache.set_wx_quotas(*wx_quotas)

            except Exception as e:
                _LOGGER.error('query_pay_types  error.(%s)' % e)
            time.sleep(10)
